﻿var statuedic;
$(function () {
	statuedic = getDictionaryByType('EVAL_SINGLETASK_STATUE');
	$(".nav-ul li").eq(4).addClass("cur");
    if ($(".form-inline div").hasClass('form-more')) {
        $('.btn-more').show();
    }
    $('.btn-clear-form').click(function () {
        $('.form-inline input').val('');
    })
	 
	query(1);
	
	$('#pageNum').dropdown();
	$('#dropdown').on('shown.bs.dropdown', function () {
	     $('.dropdown-menu li').click(function () {
	         var str = $(this).children('a').html();
	         var size = $(this).children('a').children('label').text();
	         str += '<span class="caret"></span>';
	         $("#pageNum").html(str);
	         
	         query(1);
	     })
	 });
	
	$('#idcEvaluating').change(function(){
		var changeBool = $('#idcEvaluating').is(':checked'); 
		if(changeBool){
			$('#idcEvaluating_1').removeAttr('disabled');
			$('#idcEvaluating_2').removeAttr('disabled');
		} else {
			$('#idcEvaluating_1').attr('disabled','disabled');
			$('#idcEvaluating_1').prop("checked", false);
			$('#idcEvaluating_2').attr('disabled','disabled');
			$('#idcEvaluating_2').prop("checked", false);
		}
	});
	
	$("#workFlow").on("show.bs.modal",function(e){
//		 这里的btn就是触发元素，即你点击工单流转按钮
	    var btn = $(e.relatedTarget);
	    var singleTaskId = btn.attr("value-id");
	    if(singleTaskId){
	    	$.ajax({
	    		type : "POST",
	    		url : "evalTaskFlow/getBySingleTaskId",
	    		data : {
	    			"singleTaskId" : singleTaskId
	    		},
	    		traditional: true,
	    		dataType : "json",
	    		success : function(data) {
	    			if (data.flag) {
	    				var tread = data.datas;
						insertInfoTpl(tread, $('#workFlowTread'),$('#workFlowTreadTpl'));
	    			}
	    		},
	    		error : function(data) {
	    			layer.closeAll();
	    		}
	    	});
	    }
	});
});

function jumpQuery(){
	var page = $("#jump_page").val();
	var reg = /^\+?[1-9][0-9]*$/;//判断是否为正整数 
    var flag = reg.test(trim(page));
    if(!flag){
    	layer.alert("请输入正整数！", {
			icon : 3,
			offset: '100px'
		});
    }else{
    	var totalPages = $("#total_pages").text();
    	if(parseInt(page) > parseInt(totalPages)){
    		layer.alert("跳转页数不能超过总页数！", {
    			icon : 3,
    			offset: '100px'
    		});
    	}else{
    		query(page);
    	}
    }
}

function query(page){
	layer.load(4);
	$.ajax({
		type : "POST",
		url :  "singleTask/getSingleTaskInfo",
		data : {
			'currentPage': page,
			'pageSize' : $("#pageNum").children('strong').text(),
			'userId': $('#userId').val()
		},
		dataType : "json",
		success : function(data) {
			layer.closeAll();
			if (data.flag) {
				var tread = data.datas;
				insertInfoTpl(tread, $('#tread'), $('#treadTpl'));
				var currentPage = data.currentPage;
				var totalPages = data.totalPages;
				var totalData = data.totalData;
				$("#total_data").text(totalData);
				$("#total_pages").text(totalPages);
				var options = {
					currentPage : currentPage, // 当前的请求页面。
					totalPages : totalPages, // 一共多少页。
					size : "normal", // 应该是页眉的大小。
					bootstrapMajorVersion : 3, // bootstrap的版本要求。
					alignment : "right",
					numberOfPages : 5, // 一页显示几个按钮
					itemTexts : function(type, page, current) { // 如下的代码是将页眉显示的中文显示我们自定义的中文。
						switch (type) {
						case "first":
							return "首页";
						case "prev":
							return "上一页";
						case "next":
							return "下一页";
						case "last":
							return "末页";
						case "page":
							return page;
						}
					},
					tooltipTitles : function(type, page, current) { // 提示框，当鼠标放上去给提示
						switch (type) {
						case "first":
							return "首页";
						case "prev":
							return "上一页";
						case "next":
							return "下一页";
						case "last":
							return "末页";
						}
					},
					onPageClicked : function(event, originalEvent, type, page) {
						layer.load(4);
						$.ajax({
							type : "POST",
							url : "singleTask/getSingleTaskInfo",
							data : {
								"currentPage" : page,
								"pageSize" : $("#pageNum").children('strong').text(),
								'userId': $('#userId').val()
							},
							dataType : "json",
							success : function(data) {
								if (data.flag) {
									layer.closeAll();
									var tread = data.datas;
									insertInfoTpl(tread, $('#tread'),$('#treadTpl'));
								}
							},
							error : function(data) {
								layer.closeAll();
							}
						});
					}
				}
				$('#pageLimit').bootstrapPaginator(options);
			}
		},
		error : function(data) {
			layer.closeAll();
		}
	});
}

/**
 * [insertInfoTpl 插入 html信息]
 * @param  {[type]} data [渲染所需的数据]
 * @param  {[type]} dom  [加入页面中的哪个DOM节点]
 * @return {[type]}      [description]
 */
function insertInfoTpl(data, dom, tpl) {
	dom.empty();
    var infoTpl = tpl.html()
    var compiled = _.template(infoTpl)
    var html = ''
	var columnArray = new Array();	
    	
    _.forEach(data, function (item, index) {
        item.index = index + 1
        item.statueName = getValueByKey(statuedic,item.statue+'');
        html += compiled(item)
        var map = {};
        map['statue'] = item.statue;
        map['id'] = item.id;
        columnArray.push(map)
    })
    dom.append($(html))
    for(var i=0; i<columnArray.length; i++){
    	setBtnShow(columnArray[i].statue, columnArray[i].id);
    }
}


function trim(str){ 
    return str.replace(/(^\s*)|(\s*$)/g, ""); 
}

/**
 * 添加
 * @returns {Boolean}
 */
function addSingleTask(that){
	$(that).removeAttr("data-dismiss");
	var types = new Array();
	var businessScope=$('input:radio[name="businessScope"]:checked').val();
	var userId = $('#userId').val();
	if($('#idcEvaluating').is(':checked')) {
		var idcEvaluating_1 = $('#idcEvaluating_1').is(':checked');
		var idcEvaluating_2 = $('#idcEvaluating_2').is(':checked');
		if(idcEvaluating_1 == false && idcEvaluating_2 == false){
			layer.alert("IDC业务评测(不含互联网资源协作、仅限互联网资源协作必须选择其中一个或两个)！", {
				icon : 3,
				offset: '100px'
			});
			return;
		}
	}
	if(businessScope == undefined){
		layer.alert("其选择业务范围！", {
			icon : 3,
			offset: '100px'
		});
		return;
	}
	$("[name='type']:checked").each(function(){     
		types.push($(this).val());
	 });
	if(!types.length){
		layer.alert("请选择表单类型！", {
			icon : 3,
			offset: '100px'
		});
	} else {
		$.ajax({
			type : "POST",
			url : "singleTask/add",
			data : {
				"types" : types,
				"businessScope" : businessScope,
				"userId" : userId
			},
			traditional: true,
			dataType : "json",
			success : function(data) {
				if (data.flag) {
					query(1);
				}
			},
			error : function(data) {
				console.log(errorThrown);
				layer.closeAll();
			}
		});
		$(that).attr("data-dismiss","modal");//关闭父窗口
		clearForm('addQueryForm');
	}

}

// 清空form 表单
function clearForm(id) {
    var objId = document.getElementById(id);
    if (objId == undefined) {
        return;
    }
    for (var i = 0; i < objId.elements.length; i++) {
        if (objId.elements[i].type == "text") {
            objId.elements[i].value = "";
        }
        else if (objId.elements[i].type == "password") {
            objId.elements[i].value = "";
        }
        /*else if (objId.elements[i].type == "radio") {
            objId.elements[i].checked = false;
        }*/
        else if (objId.elements[i].type == "checkbox") {
            objId.elements[i].checked = false;
        }
        else if (objId.elements[i].type == "select-one") {
            objId.elements[i].options[0].selected = true;
        }
        else if (objId.elements[i].type == "select-multiple") {
            for (var j = 0; j < objId.elements[i].options.length; j++) {
                objId.elements[i].options[j].selected = false;
            }
        }
        else if (objId.elements[i].type == "textarea") {
            objId.elements[i].value = "";
        }
    }
}

// 工单流转
function showFlow(id){
	$.ajax({
		type : "POST",
		url : "evalTaskFlow/getBySingleTaskId",
		data : {
			"singleTaskId" : id
		},
		traditional: true,
		dataType : "json",
		success : function(data) {
			if (data.flag) {
				layer.closeAll();
				var tread = data.datas;
				insertInfoTpl(tread, $('#workFlow'),$('#workFlowTreadTpl'));
			}
		},
		error : function(data) {
			layer.closeAll();
		}
	});
}

/**
 * 填写工单
 * @param statue
 * @param type
 */
function addApplication(id, statue, type, userId,form_number){
	var param = "?singleTaskId="+id+"&statue="+statue+"&type="+type+"&backViewType=1&userId="+userId+"&form_number="+form_number;
	window.location.replace("evalApplication"+param);
}

/**
 * 查看工单
 * showType：view表示当前查看
 */
function showApplication(id, statue, type, userId){
	var param = "?singleTaskId="+id+"&statue="+statue+"&type="+type+"&backViewType=1&userId="+userId+"&showType=view";
	/*if(statue == 6 || statue == 10){
		window.location.replace("evalProject"+param);
	} else {
		window.location.replace("evalApplication"+param);
	}*/
	window.location.replace("evalApplication"+param);
}

/**
 * showType：eval 表示当前查看评测记录的结果
 */
function showEval(id, statue, type, userId){
	var param = "?singleTaskId="+id+"&statue="+statue+"&type="+type+"&backViewType=1&userId="+userId+"&showType=eval";
	if(statue == 6 || statue == 10){
		window.location.replace("evalProject"+param);
	} else {
		window.location.replace("evalApplication"+param);
	}
	//window.location.replace("evalApplication"+param);
}

/**
 * 1-未填写 2-未提交(已保存) 3-已提交(未核实) 4-退回补正  5-已核实(未评测) 6-评测中  7-测试通过  8-测试不通过 9-退回修改 10-已补正
 */
function setBtnShow(statue, id){
	if(statue == 1 || statue == 2 || statue == 4 || statue == 9){ // 填写
		$('#write_'+id).removeAttr('style');
	} 
	if(statue == 1 || statue == 2){ // 删除
		$('#del_'+id).removeAttr('style');
	}
	if(statue == 2 || statue == 4 || statue == 9){ // 提交
		$('#submit_'+id).removeAttr('style');
	}
	if(statue == 3 || statue == 5 || statue == 6 || statue == 7 || statue == 8 || statue == 10){ //查看
		$('#view_'+id).removeAttr('style');
	}
	if(statue == 3 || statue ==4 || statue == 5 || statue == 6 || statue == 7 || statue == 8 || statue == 10){ //工单流转
		$('#flow_'+id).attr('style','width: 25%;');
	}
	if(statue == 6){//评测记录
		$('#evalRecord_'+id).removeAttr('style');
	}
	if(statue == 7 || statue == 8){//评测结果
		$('#evalResult_'+id).removeAttr('style');
	}
	
//	if(statue == 7 || statue == 8){ // 重新评测
//		$('#againEval_'+id).attr('style','width: 25%;');
//	}
}

/**
 * 提交
 * @param id
 * @param statue 当前状态
 */
function addTaskAudit(id, statue){
	//修改为要改变的状态
	var btnName = '提交';
	if(statue == 9){
		statue = 3; 
	} else if(statue == 4){ 
		statue = 10;
	} else if(statue == 2){
		statue = 3;
	} else if(statue == 7 || statue == 8){
		btnName = '重新提测';
		statue = 6;
		if(!confirm("确定重新提测吗？")){
			return false;
		}
	}
	$.ajax({
		type : "POST",
		url : "evalApplication/submitCdn",
		data : {
			"singleTaskId" : id,
			"statue": statue,
			"btnName": btnName
		},
		traditional: true,
		dataType : "json",
		success : function(data) {
			if (data.flag) {
				query(1);
			}
		},
		error : function(data) {
			layer.closeAll();
		}
	});
}


function del(id){
	layer.confirm('是否确定删除？', {
        btn : [ '是', '否' ], // 按钮
        offset: '100px',
        shade : false
    // 不显示遮罩
    }, function() {
        layer.load(1);
        $.ajax({
			type : "POST",
			url : "singleTask/delete",
			data : {
				"id" : id
			},
			traditional: true,
			dataType : "json",
			success : function(data) {
				if (data.flag) {
					query(1);
				}
			},
			error : function(data) {
				layer.closeAll();
			}
		});
    }, function() {
    });
}